package com.android.newsbackstage.activity;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.android.newsbackstage.R;
import com.android.newsbackstage.adapter.NewsDataAdapter;
import com.android.newsbackstage.bean.News;
import com.android.newsbackstage.util.OkHttpTool;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.OkHttpClient;

public class MainActivity extends AppCompatActivity {
    private Activity myActivity;//上下文
    private TabLayout tabTitle;
    private RecyclerView rvNewsList;
    private NewsDataAdapter mNewsAdapter;
    private SmartRefreshLayout srlRecord;//刷新
    private Gson gson=new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
    private List<Integer> state = new ArrayList<>();
    private List<String> title = new ArrayList<>();
    private Integer typeId;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myActivity = this;
        setContentView(R.layout.activity_main);
        tabTitle = (TabLayout)findViewById(R.id.tab_title);
        rvNewsList = (RecyclerView)findViewById(R.id.rv_news_list);
        srlRecord=findViewById(R.id.srl_list);
        loadTypeData();

    }
    /**
     * 初始化页面
     */
    private void initView() {
        tabTitle.setTabMode(TabLayout.MODE_SCROLLABLE);
        //设置tablayout距离上下左右的距离
        //tab_title.setPadding(20,20,20,20);
        //为TabLayout添加tab名称
        for (int i=0;i<title.size();i++){
            tabTitle.addTab(tabTitle.newTab().setText(title.get(i)));
        }
        LinearLayoutManager layoutManager=new LinearLayoutManager(myActivity);
        //=1.2、设置为垂直排列，用setOrientation方法设置(默认为垂直布局)
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        //=1.3、设置recyclerView的布局管理器
        rvNewsList.setLayoutManager(layoutManager);
        //==2、实例化适配器
        //=2.1、初始化适配器
        mNewsAdapter=new NewsDataAdapter();
        //=2.3、设置recyclerView的适配器
        rvNewsList.setAdapter(mNewsAdapter);
        typeId = state.get(0);
        loadData();
        tabTitle.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                typeId=state.get(tab.getPosition());
                loadData();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        //下拉刷新
        srlRecord.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                loadData();
                srlRecord.finishRefresh();
            }
        });
    }

    /**
     * 加载类型数据
     */
    private void loadTypeData(){
        String url= OkHttpTool.ip + "/selectType";
        Map<String,Object> map=new HashMap<>();
        OkHttpTool.httpGet(url,map , new OkHttpTool.ResponseCallback() {
            @Override
            public void onResponse(final boolean isSuccess, final int responseCode, final String response, Exception exception) {
                myActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (isSuccess && responseCode==200){
                            try {
                                JSONObject jsonObject=new JSONObject(response);
                                String data=jsonObject.getString("data");
                                Type t=new TypeToken<List<com.android.newsbackstage.bean.Type>>(){}.getType();//列表信息
                                List<com.android.newsbackstage.bean.Type> list=gson.fromJson(data,t);
                                for (com.android.newsbackstage.bean.Type type : list) {
                                    state.add(type.getId());
                                    title.add(type.getName());
                                }
                                initView();
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
            }
        });
    }

    /**
     * 加载新闻数据
     */
    private void loadData(){
        String url= OkHttpTool.ip + "/selectNewsByTypeId";
        Map<String,Object> map=new HashMap<>();
        map.put("type_id",typeId);
        OkHttpTool.httpGet(url, map, new OkHttpTool.ResponseCallback() {
            @Override
            public void onResponse(final boolean isSuccess, final int responseCode, final String response, Exception exception) {
                myActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (isSuccess && responseCode==200){
                            try {
                                JSONObject jsonObject=new JSONObject(response);
                                String data=jsonObject.getString("data");
                                Type type=new TypeToken<List<News>>(){}.getType();//列表信息
                                List<News> list=gson.fromJson(data,type);
                                if (list.size() > 0){
                                    mNewsAdapter.addItem(list);
                                }
                                srlRecord.finishRefresh();
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
            }
        });
    }
}